/*
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  Author: hakanai
 */

#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <libsdb.h>
#include <unistd.h>

#define TFILE "/tmp/d23rnst39ax.sdb"

struct record_t {
  int num;
  char str[32];
};

static int simple_update() {
  struct record_t r = { 0 }, b;
  uint16_t size = sizeof(struct record_t);
  sdb_t db;

  assert(sdb_open(TFILE, &db) == SDB_OK);

  r.num = 0;
  sprintf(r.str, "hello world");

  assert(sdb_append(&db, &r, size) == SDB_OK);

  r.num = 20;
  sprintf(r.str, "cruel world");
  assert(sdb_update(&db, 0, &r) == SDB_OK);

  assert(sdb_read(&db, 0, &b) == SDB_OK);

  assert(b.num == 20);
  assert(strcmp(b.str, "cruel world") == 0);
  sdb_close(&db);
  unlink(TFILE);

  return 0;
}

static void populate_db(sdb_t *db) {
  struct record_t r;
  uint16_t size = sizeof(struct record_t);

  for (int i = 0; i < 20; i++) {
    r.num = i;
    sprintf(r.str, "record%d", i);
    assert(sdb_append(db, &r, size) == SDB_OK);
  }
}

static int update_multiple() {
  struct record_t r, b;
  uint16_t size = sizeof(struct record_t);
  sdb_t db;

  assert(sdb_open(TFILE, &db) == SDB_OK);

  populate_db(&db);

  r.num = 42;
  sprintf(r.str, "updated second record");
  assert(sdb_update(&db, 2, &r) == SDB_OK);

  assert(sdb_update(&db, 18, &r) == SDB_OK);


  assert(sdb_read(&db, 2, &b) == SDB_OK);
  assert(strcmp(b.str, "updated second record") == 0);

  assert(sdb_read(&db, 17, &b) == SDB_OK);
  assert(strcmp(b.str, "updated second record") != 0);

  assert(sdb_read(&db, 18, &b) == SDB_OK);
  assert(strcmp(b.str, "updated second record") == 0);
  assert(b.num == 42);

  sdb_close(&db);
  unlink(TFILE);
  return 0;
}

int main() {
  unlink(TFILE);
  assert(!simple_update());
  assert(!update_multiple());
  return 0;
}

